# -*- coding: utf-8 -*-
"""
@Time    : 2024/6/24 11:38 
@Author  : ZhangShenao 
@File    : http_response.py 
@Desc    : Http响应定义
"""
from dataclasses import field, dataclass
from typing import Any

from flask import jsonify

from .http_status_code import HttpStatusCode


@dataclass
class HttpResponse:
    """通用Http响应格式"""

    code: HttpStatusCode = HttpStatusCode.SUCCESS  # Http状态码
    message: str = ""  # 响应信息提示
    data: Any = field(default_factory=dict)  # 响应数据


def json(data: HttpResponse = None):
    """基础的响应接口"""
    return jsonify(data), 200  # 在Http协议层固定返回200,根据业务状态码处理执行结果


def success(data: Any = None):
    """成功数据响应"""
    return json(HttpResponse(code=HttpStatusCode.SUCCESS, message="", data=data))


def fail(data: Any = None):
    """失败数据响应"""
    return json(HttpResponse(code=HttpStatusCode.FAIL, message="", data=data))


def validate_error(errors: dict = None):
    """数据验证错误响应"""
    first_key = next(iter(errors))
    if first_key is not None:
        msg = errors.get(first_key)[0]
    else:
        msg = ""
    return json(HttpResponse(code=HttpStatusCode.VALIDATE_ERROR, message=msg, data=errors))


def message(code: HttpStatusCode = None, msg: str = ""):
    """基础的消息响应，固定返回消息提示，数据固定为空字典"""
    return json(HttpResponse(code=code, message=msg, data={}))


def success_with_message(msg: str = ""):
    """成功的消息响应"""
    return message(code=HttpStatusCode.SUCCESS, msg=msg)


def fail_with_message(msg: str = ""):
    """失败的消息响应"""
    return message(code=HttpStatusCode.FAIL, msg=msg)


def not_found_with_message(msg: str = ""):
    """未找到消息响应"""
    return message(code=HttpStatusCode.NOT_FOUND, msg=msg)


def unauthorized_with_message(msg: str = ""):
    """未授权消息响应"""
    return message(code=HttpStatusCode.UNAUTHORIZED, msg=msg)


def forbidden_with_message(msg: str = ""):
    """无权限消息响应"""
    return message(code=HttpStatusCode.FORBIDDEN, msg=msg)
